<script lang="ts" setup>
import { ref, reactive, onMounted, h } from 'vue';
import { Card, Table, Button, Input, Space, Form, Modal, message } from 'ant-design-vue';
import type { TableColumnsType, FormInstance } from 'ant-design-vue';
import { getFreelancerListApi, createFreelancerApi, type FreelancerApi } from '#/api/core/freelancer';

type SortField = 'name' | 'phone' | 'status' | 'created_at';

type FreelancerRecord = FreelancerApi.FreelancerRecord & {
  status_label?: string;
  task_names?: string[];
  verification_status_label?: string;
};

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

const loading = ref(false);
const dataSource = ref<FreelancerRecord[]>([]);

const searchForm = reactive({
  name: '',
  phone: '',
  id_card: '',
});

const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
});

const sortField = ref<SortField>('name');
const sortOrder = ref<'asc' | 'desc'>('asc');

const columns: TableColumnsType<FreelancerRecord> = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
    sorter: true,
    ellipsis: true,
    defaultSortOrder: 'ascend',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 140,
    sorter: true,
  },
  {
    title: '身份证号',
    dataIndex: 'id_card',
    key: 'id_card',
    width: 200,
    ellipsis: true,
  },
  {
    title: '银行卡号',
    dataIndex: 'bank_account',
    key: 'bank_account',
    width: 200,
    ellipsis: true,
    customRender: ({ record }) => record.bank_account || '-',
  },
  {
    title: '认证状态',
    dataIndex: 'verification_status',
    key: 'verification_status',
    width: 120,
    customRender: ({ record }) => record.verification_status_label || record.verification_status || '-',
  },
  {
    title: '所在任务',
    key: 'tasks',
    width: 220,
    ellipsis: true,
    customRender: ({ record }) => {
      if (!record.task_names || record.task_names.length === 0) {
        return h('span', { class: 'text-gray-400' }, '暂无任务');
      }
      const text = record.task_names.join(', ');
      return h('span', { title: text }, text);
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180,
    sorter: true,
    customRender: ({ text }) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
  },
];

const fetchData = async () => {
  try {
    loading.value = true;
    const params: FreelancerApi.FreelancerListParams = {
      page: pagination.current,
      per_page: pagination.pageSize,
      name: searchForm.name.trim() || undefined,
      phone: searchForm.phone.trim() || undefined,
      id_card: searchForm.id_card.trim() || undefined,
      sort_by: sortField.value,
      sort_order: sortOrder.value,
    };

    const response = await getFreelancerListApi(params);

    dataSource.value = response.data ?? [];
    pagination.total = response.total ?? 0;
    pagination.current = response.current_page ?? 1;
  } catch (error) {
    console.error('获取自由职业者列表失败:', error);
    message.error('获取自由职业者列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

const handleReset = () => {
  searchForm.name = '';
  searchForm.phone = '';
  searchForm.id_card = '';
  pagination.current = 1;
  sortField.value = 'name';
  sortOrder.value = 'asc';
  fetchData();
};

const handleTableChange = (paginationParams: any, _filters: any, sorter: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;

  const field = sorter?.field as SortField | undefined;
  if (field && ['name', 'phone', 'status', 'created_at'].includes(field)) {
    sortField.value = field;
    sortOrder.value = sorter.order === 'descend' ? 'desc' : 'asc';
  }

  fetchData();
};

const addModalVisible = ref(false);
const addFormRef = ref<FormInstance>();
const addSubmitting = ref(false);

const addForm = reactive({
  name: '',
  phone: '',
  id_card: '',
  bank_account: '',
  bank_name: '',
});

const addRules = {
  name: [{ required: true, message: '请输入真实姓名' }],
  phone: [{ required: true, message: '请输入手机号' }],
  id_card: [{ required: true, message: '请输入证件号码' }],
  bank_account: [{ required: true, message: '请输入银行卡号' }],
};

const openAddModal = () => {
  addModalVisible.value = true;
};

const handleAddCancel = () => {
  addModalVisible.value = false;
  addFormRef.value?.resetFields();
};

const handleAddSubmit = async () => {
  if (!addFormRef.value) return;

  try {
    await addFormRef.value.validate();

    addSubmitting.value = true;

    await createFreelancerApi({
      name: addForm.name.trim(),
      phone: addForm.phone.trim(),
      id_card: addForm.id_card.trim(),
      bank_account: addForm.bank_account.trim(),
      bank_name: addForm.bank_name.trim() || undefined,
    });

    message.success('添加成功');
    addModalVisible.value = false;
    addFormRef.value?.resetFields();
    fetchData();
  } catch (error: any) {
    if (error?.errorFields) {
      return;
    }
    const responseData = error?.response?.data;
    const errorMsg = responseData?.message || error?.message;
    message.error(errorMsg || '添加失败，请稍后重试');
  } finally {
    addSubmitting.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="p-4 space-y-4">
    <div>
      <h1 class="text-2xl font-semibold text-gray-900">自由职业者管理</h1>
      <p class="text-gray-500 mt-1">查看并维护平台注册的自由职业者信息</p>
    </div>

    <Card>
      <Form layout="inline" :model="searchForm">
        <Form.Item label="姓名">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入姓名"
            style="width: 160px"
            allowClear
            @pressEnter="handleSearch"
          />
        </Form.Item>
        <Form.Item label="手机号">
          <Input
            v-model:value="searchForm.phone"
            placeholder="请输入手机号"
            style="width: 160px"
            allowClear
            @pressEnter="handleSearch"
          />
        </Form.Item>
        <Form.Item label="身份证号">
          <Input
            v-model:value="searchForm.id_card"
            placeholder="请输入身份证号"
            style="width: 200px"
            allowClear
            @pressEnter="handleSearch"
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch" :loading="loading">查询</Button>
            <Button @click="handleReset">重置</Button>
            <Button type="primary" ghost @click="openAddModal">手动添加</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>

    <Card>
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        row-key="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: pagination.showSizeChanger,
          showQuickJumper: pagination.showQuickJumper,
          pageSizeOptions: pagination.pageSizeOptions,
          showTotal: pagination.showTotal,
        }"
        @change="handleTableChange"
      />
    </Card>

    <Modal
      v-model:open="addModalVisible"
      title="手动添加自由职业者"
      :confirm-loading="addSubmitting"
      destroy-on-close
      @ok="handleAddSubmit"
      @cancel="handleAddCancel"
    >
      <Form ref="addFormRef" :model="addForm" :rules="addRules" layout="vertical">
        <Form.Item label="真实姓名" name="name">
          <Input v-model:value="addForm.name" placeholder="请输入真实姓名" />
        </Form.Item>
        <Form.Item label="手机号" name="phone">
          <Input v-model:value="addForm.phone" placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item label="证件号码" name="id_card">
          <Input v-model:value="addForm.id_card" placeholder="请输入证件号码" />
        </Form.Item>
        <Form.Item label="银行卡号" name="bank_account">
          <Input v-model:value="addForm.bank_account" placeholder="请输入银行卡号" />
        </Form.Item>
        <Form.Item label="开户银行" name="bank_name">
          <Input v-model:value="addForm.bank_name" placeholder="请输入开户银行 (选填)" />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>
